<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="资金借入" name="borrow">
          <el-table
            :data="borrows"
            border
            v-loading="listLoading"
            fit
            size="small"
            highlight-current-row
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column
              type="index"
              label="#"
              align="center"
              width="120px;"
            ></el-table-column>
            <el-table-column
              v-for="item in tableColumns"
              :key="item.key"
              align="center"
              :label="item.title"
              :prop="item.key"
              :formatter="dataFormatter"
            >
            </el-table-column>
            <el-table-column align="center" label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getBorrowLendList"
          />
        </el-tab-pane>
        <el-tab-pane label="资金借出" name="lend">
          <el-table
            :data="lends"
            border
            v-loading="listLoading"
            fit
            size="small"
            highlight-current-row
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column
              type="index"
              label="#"
              align="center"
              width="120px;"
            ></el-table-column>
            <el-table-column
              v-for="item in tableColumns"
              :key="item.key"
              align="center"
              :label="item.title"
              :prop="item.key"
              :formatter="dataFormatter"
            >
            </el-table-column>
            <el-table-column align="center" label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getBorrowLendList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        size="small"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="单号" prop="order_no" v-if="dialogType === 'edit'">
          <el-input
            type="text"
            v-model="form.order_no"
            placeholder="单号"
            maxlength="24"
            disabled
          />
        </el-form-item>
        <el-form-item label="时间" prop="oper_time">
          <el-date-picker
            v-model="form.oper_time"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择开单时间"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="姓名" prop="person">
          <el-select v-model="form.person" placeholder="姓名" clearable>
            <el-option
              v-for="item in employees"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account_type">
          <el-select
            v-model="form.account_type"
            :placeholder="title + '账号'"
            clearable
          >
            <el-option
              v-for="item in banks"
              :label="item.account"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" placeholder="金额" clearable>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.desc" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="mini" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="HandleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getBorrowLends,
  addBorrowLend,
  updateBorrowLend,
  delBorrowLend,
} from "@/api/borrow";
import { getBanks } from "@/api/bank";
import { getEmployeeList } from "@/api/employee";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  order_no: "",
  oper_time: getCurrentDate(),
  person: null,
  account_type: null,
  category: null,
  money: 0,
  desc: "",
  user: undefined,
};

export default {
  name: "BorrowLend",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        person: [{ required: true, message: "请选择员工", trigger: "blur" }],
        oper_time: [{ required: true, message: "请输入时间", trigger: "blur" }],
        account_type: [
          { required: true, message: "请选择账号", trigger: "blur" },
        ],
        money: [{ required: true, validator: checkMoney, trigger: "blur" }],
      },

      title: "借入借出",
      borrows: [],
      lends: [],
      employees: [],
      accountList: [],
      banks: [],
      selectedKeys: [],
      activeName: "borrow",
      category: 1, //借入
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        category: 1,
        name: undefined,
        search_date: "",
      },

      tableColumns: [
        {
          key: "order_no",
          title: "单号",
        },
        {
          key: "oper_time",
          title: "时间",
        },
        {
          key: "person_name",
          title: "姓名",
        },

        {
          key: "acc_type_name",
          title: "账号",
        },
        {
          key: "money",
          title: "金额",
          filter: true,
        },
        {
          key: "desc",
          title: "备注",
        },
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      if (this.activeName == "borrow") {
        this.title = "资金借入";
      } else if (this.activeName == "lend") {
        this.title = "资金借出";
      }
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getBorrowLendList();
    this.getEmployeeList();
    this.getBankList();
  },
  methods: {
    getBorrowLendList() {
      this.listLoading = true;
      getBorrowLends(this.listQuery)
        .then((res) => {
          this.total = res.count;
          if (this.activeName == "borrow") {
            this.borrows = res.results;
          } else {
            this.lends = res.results;
          }

          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    handleTabClick(tab, event) {
      if (tab.name == "borrow") {
        this.category = 1;
      } else {
        this.category = 2;
      }
      this.listQuery.category = this.category;
      this.getBorrowLendList();
    },
    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getBankList() {
      getBanks().then((res) => {
        this.banks = res;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "money") {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getBorrowLendList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.form.category = this.category;
      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delBorrowLend(row.id);
          this.getBorrowLendList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateBorrowLend(this.form);
        } else {
          this.form.user = this.uid;
          res = await addBorrowLend(this.form);
        }
        const { id } = res;
        if (id > 0) {
          this.getBorrowLendList();
        }

        const { order_no, person_name, money } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>姓名: ${person_name}</div>
              <div>金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
    // handleChange(value) {
    //   console.log("selectedKeys:", this.selectedKeys);
    //   if (this.selectedKeys.length > 0) {
    //     this.incomeForm.acc_title = this.selectedKeys[
    //       this.selectedKeys.length - 1
    //     ];
    //   } else {
    //     this.incomeForm.acc_title = undefined;
    //   }
    // },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>